package dto

import (
	"encoding/json"
	"github.com/honwee/awm/internal/model"
	"time"
)

// TraceResponse 追踪日志响应DTO
type TraceResponse struct {
	// 追踪日志ID
	ID uint64 `json:"id" example:"1"`
	// 事件类型（workflow_started/workflow_finished/node_started/node_finished）
	Event string `json:"event" example:"workflow_started"`
	// 工作流运行ID
	WorkflowRunID string `json:"workflow_run_id" example:"15ca1ffd-097a-4d86-8565-3900a216f848"`
	// 工作流ID
	WorkflowID string `json:"workflow_id" example:"e1bcf123-beb7-436c-97a2-c3b12390658d"`
	// 节点运行ID
	NodeRunID string `json:"node_run_id" example:"50570e0e-8cf3-45f1-8d29-64705a7eee44"`
	// 节点ID
	NodeID string `json:"node_id" example:"1736996589701"`
	// 节点类型（0-工作流节点，1-组件节点）
	Type int8 `json:"type" example:"0"`
	// 详细数据（JSON格式）
	Data interface{} `json:"data"`
	// 创建时间
	CreatedAt time.Time `json:"created_at"`
}

// FromModel 从模型转换为DTO
func (t *TraceResponse) FromModel(trace *model.Trace) {
	t.ID = trace.ID
	t.Event = trace.Event
	t.WorkflowRunID = trace.WorkflowRunID
	t.WorkflowID = trace.WorkflowID
	t.NodeRunID = trace.NodeRunID
	t.NodeID = trace.NodeID
	t.Type = trace.Type

	// 解析JSON数据
	var data interface{}
	if err := json.Unmarshal(trace.Data, &data); err == nil {
		t.Data = data
	}

	t.CreatedAt = trace.CreatedAt
}

// TraceListResponse 追踪日志列表响应
type TraceListResponse struct {
	// 分页信息
	Pagination *PaginationResponse `json:"pagination"`
	// 追踪日志列表
	Traces []TraceResponse `json:"traces"`
}

// FromModelList 从模型列表转换为响应
func (r *TraceListResponse) FromModelList(traces []model.Trace, page, pageSize int, total int64) {
	r.Traces = make([]TraceResponse, len(traces))
	for i, trace := range traces {
		r.Traces[i] = TraceResponse{}
		r.Traces[i].FromModel(&trace)
	}
	r.Pagination.FromParams(page, pageSize, total)
}
